﻿define([
  'models/abmManagers/userManager',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmTableTmp.html',
  'text!templates/abmManagers/user/common/userManager.html',
], function (Manager, BaseTmp, TableTmp, UniqTmp) {

    var view = Backbone.View.extend({
        el: $("#main"),
        _uId: "",
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-user']").remove();
            var model = new Manager();
            var _this = this;
            this._uId = $.uuid();
            var cpyId = __currentSession.companyId;
            model.List(cpyId, function (dataUser) {
                var baseTemplate = Handlebars.compile(BaseTmp);
                var tableTemplate = Handlebars.compile(TableTmp);
                var uniqTemplate = Handlebars.compile(UniqTmp);

                var dataBaseTemplate = {
                    id: _this._uId,
                    dataRel: "abm-user", // cuidado, ref en js
                    tmpClass: "user-manager", // cuidado, ref en css
                    title: translate("_userManager")
                };
                var dataTableTemplate = {
                    headers: [translate("_name"), translate("_login"), translate("_email"),
                        translate("_groups"), translate("_rol"), translate("_options")]
                };
                var dataUniqTemplate = {
                    data: dataUser,
                    cpyIdGroupComp: cpyId,
                    cpyIdRolComp: cpyId
                };
                
                var html = baseTemplate(dataBaseTemplate);
                var html2 = tableTemplate(dataTableTemplate);
                var html3 = uniqTemplate(dataUniqTemplate);

                _this.$el.append(html);
                $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
                $("div[data-id='" + _this._uId + "']").find("tbody").append(html3);

                postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));

                _this.addTableHandlers($("div[data-id='" + _this._uId + "']").find("table"));
                $("div[data-id='" + _this._uId + "']").find("table").cubeTable();
                $('<a href="#" class="btn btn-adduser"><i class="icon-plus"></i></a>').appendTo('div.data-table-options');

                _this.addHandlers();
                $("#mainLoading").hide();
            });
        },
        edit: function (e) {
            var userId = $(e.currentTarget).closest("tr").attr("data-id");

            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).showEdit(userId);
            });
        },
        editPreferences: function (e) {
            var id = $(e.currentTarget).closest("tr").attr("data-id");

            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).showEditPref(id);
            });
        },
        deleteUser: function (e) {
            var id = $(e.currentTarget).closest("tr").attr("data-id");

            require(['controllers/common/showModal'], function (Controller) {
                (new Controller()).show(
                    {
                        title: translate("_deleteUser"),
                        text: translate("_sure_delete_user"),
                        buttons: [
                            { "title": translate("yes"), "css": "primary", "code": "yes" },
                            { "title": translate("no"), "code": "no" }
                        ],
                        callback: function (code) {
                            if (code == "yes") {
                                var model = new Manager();
                                $("#mainLoading").show();
                                model.DeleteUser(id, function () {
                                    $("#mainLoading").hide();
                                    require(['controllers/abmManagers/userManager'], function (Controller) {
                                        (new Controller()).show();
                                    });
                                });
                            }
                        }
                    });
            });
        },
        changeState: function (e) {
            var userId = $(e.currentTarget).closest("tr").attr("data-id");
            var stateActual = $(e.currentTarget).val();
            var modelUser = new Manager();

            modelUser.GetUser(userId, function (dataUser) {
                dataUser.active = !dataUser.active;
                var data = {
                    user: dataUser
                }
                modelUser.Update(dataUser, function () {
                    // todo, avisar del cambio al usuario?
                });
            });
        },
        addUser: function () {
            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).addUser();
            });
        },
        close: function () {
            var key = $("#currentTask").attr("data-rel");
            require(['controllers/home/home'], function (Controller) {
                (new Controller()).removeTask(key);
            });
        },
        addTableHandlers: function (oTable) {
            $(oTable).find("button.btn-edit").on("click", this.edit);
            $(oTable).find("button.btn-preference").on("click", this.editPreferences);
            $(oTable).find("input.user-state").on("click", this.changeState);
            $(oTable).find("button.btn-delete").on("click", this.deleteUser);
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("div.data-table-options a.btn-adduser").on("click", this.addUser);
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.close);
        }
    });
    return view;
});